package cn.pconline.autoclub.web.wap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubAwardRecord;
import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.UpgradeGift;
import cn.pconline.autoclub.entity.UpgradeGiftReward;
import cn.pconline.autoclub.entity.UpgradeRule;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubAwardRecordService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.UpgradeGiftRewardService;
import cn.pconline.autoclub.service.UpgradeGiftService;
import cn.pconline.autoclub.service.UpgradeRuleService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.web.UserAuth;
import cn.pconline.passport2.Passport;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
/**
 * Action - 升星
 * @author zhoutianhuai
 *
 * 2015年4月23日 下午5:04:20
 */
@Controller
@RequestMapping("/wap/uplevel")
public class UpGradeLevelAction {
	@Autowired
	private UpgradeGiftService upgradeGiftService;
	@Autowired
	private UpgradeGiftRewardService upgradeGiftRewardService;
	@Autowired
	private UpgradeRuleService upgradeRuleService;
	@Autowired
	private GeliDao geliDao;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private ClubAwardRecordService recordService;
    @Autowired
    private Passport passport;
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(UpGradeLevelAction.class);
    final static int GIFT_PAGE_SIZE = 15;
    final static int INPUT_MAX_LENGTH = 30;
    // 5: 人数油值满足
    static final int CAN_UP_LEVEL = 5;
    private String getLoginUrl(String returnUri) {
        return systemConfig.getUcWapRoot() + "/passport/login.jsp?return=" + systemConfig.getWapRoot() + returnUri;
    }
    
    
    /**
     * 礼品列表列表页
     * for APP(WAP暂时没用到)
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/goSelectUpgradeGift.do", method = RequestMethod.GET)
    public String goSelectUpgradeGift(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        String from = WebUtils.param(request, "from", "app");
        if (club == null) {
        	   log.warn("not found club: {}", clubId);
               return "redirect:" + systemConfig.getWapRoot();
        }
        request.setAttribute("userSessionName", systemConfig.getUserSessionName());
        request.setAttribute("commonsessionId",passport.recognize(request, resp).getSessionId());
        request.setAttribute("from", from);
        User user = userAuth.getUser(request, resp);
        if (!memberService.isClubOwner(user.getUid(), clubId)) {
        	 log.warn("not club admin: {}", user.getUid());
             if (!"wap".equals(from)) {
                 return "redirect:pcation://goback";
             } else {
                 return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
             }
        }
        int isValid = clubLevelService.isUpLevel(club);
        ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
        if (isValid == CAN_UP_LEVEL &&  nextLevel != null) {
        	 UpgradeRule rule = upgradeRuleService.findUpgradeRuleByLevelId(nextLevel.getLevelId());
              Pager<UpgradeGift> pager = upgradeGiftService.pageUpgradeGift(1, GIFT_PAGE_SIZE, nextLevel.getLevelId());
              long requireValuePoint = 0;
              if (nextLevel.getLevelId() == ClubLevel.LEVEL_ONE && pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                  for(UpgradeGift upgradeGift : pager.getResultList()){
                  	if(upgradeGift.getIsRequired() == UpgradeGift.REQUIRED_YES){
                  		requireValuePoint += upgradeGift.getValuePoint();
                  	}
                  }
              }
              
              request.setAttribute("isValid", isValid);
              request.setAttribute("clubLevel", nextLevel);
              request.setAttribute("pager", pager);
              request.setAttribute("requireValuePoint", requireValuePoint);
              request.setAttribute("levelId", nextLevel.getLevelId());
              request.setAttribute("clubId", clubId);
              request.setAttribute("rule", rule);
        } else {
        	   log.warn("not next level: {}", club.getLevelId());
               if (!"wap".equals(from)) {
                   return "redirect:pcation://goback";
               } else {
                   return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
               }
        }
        
        return "template/wap/uplevel/selectGift";
    }
   
    /**
     * 到确定礼包选择页面
     * for APP(WAP暂时没用到)
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/goUpgradeGiftInfo.do", method = RequestMethod.GET)
    public String goUpgradeGiftInfo(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long levelId = WebUtils.paramLong(request, "levelId", 0);
        String giftStr = WebUtils.param(request, "giftStr", "");
        String from = WebUtils.param(request, "from", "app");
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
     	   log.warn("not found club: {}", clubId);
            return "redirect:" + systemConfig.getWapRoot();
        }
         request.setAttribute("userSessionName", systemConfig.getUserSessionName());
         request.setAttribute("commonsessionId",passport.recognize(request, resp).getSessionId());
         request.setAttribute("from", from);
        User user = userAuth.getUser(request, resp);
       if (!memberService.isClubOwner(user.getUid(), clubId)) {
    	   log.warn("not club admin: {}", user.getUid());
           if (!"wap".equals(from)) {
               return "redirect:pcation://goback";
           } else {
               return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
           }
        }
        List<Map<String, Object>> giftMapList = new ArrayList<Map<String, Object>>();
        int isValid = clubLevelService.isUpLevel(club);
        ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
        if (isValid == CAN_UP_LEVEL &&  nextLevel != null) {
        	  ClubAwardRecord awardRecord = recordService.findByClubId(clubId, nextLevel.getLevelId());
        	 if(!giftStr.equals("")){
        	 try {
				JSONArray jsonArray = JSONArray.parseArray(giftStr);
				 if (jsonArray != null && !jsonArray.isEmpty()) {
				 	for(int i=0; i<jsonArray.size(); i++){
				 		JSONObject jsonObject = jsonArray.getJSONObject(i);
				 		Map<String, Object> map = new HashMap<String, Object>();
				 		long giftId = jsonObject.getLongValue("giftId");
				 		int num = jsonObject.getIntValue("num");
				 		long totalValuePoint = jsonObject.getLongValue("valuePoint");
				 		UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
				 		if(gift !=null){
				 			map.put("name", gift.getName());
				 		}
				 		map.put("giftId", giftId);
				 		map.put("num", num);
				 		map.put("totalValuePoint", totalValuePoint);
				 		giftMapList.add(map);
				 	}
				 }
			} catch (JSONException e) {  
				  log.error("error", e);
			}
        	}
              request.setAttribute("giftMapList", giftMapList);
              request.setAttribute("clubLevel", nextLevel);
              request.setAttribute("levelId", nextLevel.getLevelId());
              request.setAttribute("clubId", clubId);
              request.setAttribute("address", awardRecord);
              request.setAttribute("giftStr", giftStr);
              request.setAttribute("myClubUrl", club.getClubUrl());
        } else {
        	  log.warn("not next level: {}", club.getLevelId());
              if (!"wap".equals(from)) {
                  return "redirect:pcation://goback";
              } else {
                  return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
              }
        }
        return "template/wap/uplevel/selectGiftInfo";
    }
    

    /**
     * 去到编辑
     * for APP(WAP暂时没用到)
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/goEditAddress.do", method = RequestMethod.GET)
    public String goEditAddress(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        String giftStr = WebUtils.param(request, "giftStr", "");
        Club club = clubService.getValidClub(clubId);
        String from = WebUtils.param(request, "from", "app");
        if (club == null) {
     	   log.warn("not found club: {}", clubId);
            return "redirect:" + systemConfig.getWapRoot();
        }
         request.setAttribute("userSessionName", systemConfig.getUserSessionName());
         request.setAttribute("commonsessionId",passport.recognize(request, resp).getSessionId());
         request.setAttribute("from", from);
        User user = userAuth.getUser(request, resp);
       if (!memberService.isClubOwner(user.getUid(), clubId)) {
    	   log.warn("not club admin: {}", user.getUid());
           if (!"wap".equals(from)) {
               return "redirect:pcation://goback";
           } else {
               return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
           }
        }
       int isValid = clubLevelService.isUpLevel(club);
       ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
       if (isValid == CAN_UP_LEVEL &&  nextLevel != null) {
        	  ClubAwardRecord awardRecord = recordService.findByClubId(clubId, nextLevel.getLevelId());
              request.setAttribute("clubId", clubId);
              request.setAttribute("address", awardRecord);
              request.setAttribute("levelId", nextLevel.getLevelId());
              request.setAttribute("giftStr", giftStr);
        } else {
        	  log.warn("not next level: {}", club.getLevelId());
              if (!"wap".equals(from)) {
                  return "redirect:pcation://goback";
              } else {
                  return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
              }
        }
        return "template/wap/uplevel/editAddress";
    }
    
    /**
     * 修改收货地址
     * for APP(WAP暂时没用到)
     *
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/updateAddress.do", method = RequestMethod.POST)
    public String updateAddress(HttpServletRequest request, HttpServletResponse resp) {
        try {
            long clubId = WebUtils.paramLong(request, "clubId", 0);
            long levelId = WebUtils.paramLong(request, "levelId", 0);
            String from = WebUtils.param(request, "from", "app");
            Club club = clubService.getValidClub(clubId);
            if (club == null) {
         	   log.warn("not found club: {}", clubId);
                return "redirect:" + systemConfig.getWapRoot();
            }
             request.setAttribute("userSessionName", systemConfig.getUserSessionName());
             request.setAttribute("commonsessionId",passport.recognize(request, resp).getSessionId());
             request.setAttribute("from", from);
            User user = userAuth.getUser(request, resp);
           if (!memberService.isClubOwner(user.getUid(), clubId)) {
        	   log.warn("not club admin: {}", user.getUid());
               if (!"wap".equals(from)) {
                   return "redirect:pcation://goback";
               } else {
                   return "redirect:" + systemConfig.getWapRoot() + "/" + club.getClubUrl();
               }
            }
            String name = WebUtils.paramTrim(request, "name", "");
            String phone = WebUtils.paramTrim(request, "phone", "");
            String address = WebUtils.paramTrim(request, "address", "");
            String postalCode = WebUtils.paramTrim(request, "postalCode", "");
            if (StringUtils.isEmpty(name) || name.length() > 20) {
                this.errorMsg(resp, "名字不能为空或名字过长", null);
                return null;
            }
            if (StringUtils.isEmpty(phone) || phone.length() > 20) {
                this.errorMsg(resp, "联系方式不能为空或过长", null);
                return null;
            }
            if (StringUtils.isEmpty(address) || address.length() > 100) {
                this.errorMsg(resp, "地址不能为空或地址过长", null);
                return null;
            }
            if (StringUtils.isEmpty(postalCode) || postalCode.length() > 6) {
                this.errorMsg(resp, "邮编不能为空或邮编过长", null);
                return null;
            }
            ClubAwardRecord awardRecord = recordService.findByClubId(clubId, levelId);

            if (awardRecord == null) {
                int isUp = clubLevelService.isUpLevel(club);
                if (isUp < 4 && isUp > 0) {
                    this.errorMsg(resp, "未达到领取福利标准，无法修改收货人信息", null);
                    return null;
                } else if (isUp == 5) {
                    ClubAwardRecord awRecord = new ClubAwardRecord();
                    awRecord.setClubId(clubId);
                    awRecord.setLevelId(levelId);
                    awRecord.setUpdateTime(DateUtils.getNow());
                    awRecord.setName(name);
                    awRecord.setPhone(phone);
                    awRecord.setAddress(address);
                    awRecord.setPostalCode(postalCode);
                    recordService.create(awRecord);
                    this.successMsg(resp, "修改成功");
                }
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                this.errorMsg(resp, "该级别福利已经领取，无法修改收货人信息！", null);
                return null;
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                awardRecord.setName(name);
                awardRecord.setPhone(phone);
                awardRecord.setAddress(address);
                awardRecord.setPostalCode(postalCode);
                recordService.update(awardRecord);
                this.successMsg(resp, "修改成功");
            }
        } catch (Exception ex) {
            this.errorMsg(resp, "修改出错了", null);
        }
        return null;
    }
    
    /**
     * 升级车友会
     *
     * @author fxr
     * @param request
     * @param response
     * @return
     * @
     */
    @ResponseBody
    @RequestMapping(value = "/upgradeClubLevel.do", method = RequestMethod.POST)
    public void upgradeClubLevel(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long levelId = WebUtils.paramLong(request, "levelId", 0);
        String giftStr = WebUtils.param(request, "giftStr", "");
        String from = WebUtils.param(request, "from", "app");
        if (levelId < 1) {
            this.errorMsg(response, "参数非法!", null);
            return;
        }
        if (giftStr.equals("")) {
            this.errorMsg(response, "参数非法!", null);
            return;
        }
        Club oldclub = clubService.getValidClub(clubId);
        if (oldclub == null) {
            this.errorMsg(response, "车友会不存在!", null);
            return;
        }
        // 是否登录
        request.setAttribute("userSessionName", systemConfig.getUserSessionName());
        request.setAttribute("commonsessionId",passport.recognize(request, response).getSessionId());
        request.setAttribute("from", from);
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            this.errorMsg(response, "您是游客，请登录后再操作", null);
            return;
        }
        // 是否会长
        ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
        if (clubMember == null || !clubMember.isAdmin()) {
            this.errorMsg(response, "您不是会长，无法操作!", null);
            return;
        }

        if (oldclub.getStatus() == Club.STATUS_LOCK) {
            this.errorMsg(response, "车友会已经被锁定，无法操作!", null);
            return;
        }

        if (oldclub.getStatus() == Club.STATUS_REJECTED) {
            this.errorMsg(response, "车友会已经被封，无法操作!", null);
            return;
        }
        int result = clubLevelService.isUpLevel(oldclub);
        if (result != 5) {
            this.errorMsg(response, "该车友会未满足升级条件!", null);
            return ;
        }
        //升级操作
        Map<Boolean, String> info = clubService.updateClubLevel(clubId, levelId);
        if (info.containsKey(true)) {
            ClubAwardRecord c = recordService.findByClubId(clubId, levelId);
            Club club = clubService.getValidClub(clubId);
            if (club == null) {
                this.errorMsg(response, "车友会已经被锁定，无法操作!", null);
                return;
            }
            if (c.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                c.setReceived(ClubAwardRecord.RECEIVED_YES);
                c.setAcceptDate(DateUtils.getNow());//更新领奖时间
                recordService.update(c);
                JSONArray jsonArray = JSONArray.parseArray(giftStr);
                StringBuilder giftInfo = new StringBuilder();
                if (jsonArray != null && !jsonArray.isEmpty()) {
                	ClubAwardRecord awardRecord = recordService.findByClubId(clubId, levelId);
                	for(int i=0; i<jsonArray.size(); i++){
                		JSONObject jsonObject = jsonArray.getJSONObject(i);
                		UpgradeGiftReward giftReward = new UpgradeGiftReward();
                		long giftId = jsonObject.getLongValue("giftId");
                		int num = jsonObject.getIntValue("num");
                		long totalValuePoint = jsonObject.getLongValue("valuePoint");
                		UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
                		if(awardRecord != null){
                			giftReward.setAddress(awardRecord.getAddress());
                			giftReward.setClubId(clubId);
                			giftReward.setCreateAt(new Date());
                			giftReward.setGiftId(giftId);
                			giftReward.setNum(num);
                			giftReward.setPhone(awardRecord.getPhone());
                			giftReward.setValuePoint(totalValuePoint);
                			giftReward.setTrueName(awardRecord.getName());
                			giftReward.setUserId(user.getUid());
                			giftReward.setUpdateAt(new Date());
                			giftReward.setPostcode(awardRecord.getPostalCode());
                			giftReward.setStatus(UpgradeGiftReward.STATUS_NOSEND);
                			 long id = geliDao.create(giftReward);
                			  if (id > 0) {
                				  if(gift !=null){
                		        	 if (gift.getCurNum() > 0) {
                		                 gift.setCurNum(gift.getCurNum() - num);
                		                 //会长礼品信息
	            		                 giftInfo.append(gift.getName()).append("x").append(num).append(",");
                		             }
                		        	 upgradeGiftService.updateUpgradeGift(gift);
                				  }
                		    }
                		}
                		
                		
                	}
                }
                this.successMsg(response, "领取成功，太平洋汽车网会尽快将福利快递给您，请您注意查收！");
                //给所有车友会成功发送升级信息,只有在第一次升级的时候才会发信息
               clubLevelService.setMsgToMember(clubId, giftInfo.toString());
                //升级成功发MQ到论坛同步任务状态
                clubLevelService.sendUpgrade(club); 
                return;
            } else if (c.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                this.errorMsg(response, "该级别福利已领取", null);
                return ;
            } else {
                this.errorMsg(response, "车友会升级失败", null);
                return ;
            }
        } else {
            this.errorMsg(response, info.get(false), null);
        }

        return;
    }
    /**
     * ajax操作的错误信息提示
     *
     * @param resp
     * @param msg
     * @param field
     * @
     */
    private void errorMsg(HttpServletResponse resp, String msg, String field) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", -1)
                    .put("field", field)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("errorMsg response out error");
        }
    }

    /**
     * ajax操作的成功信息提示
     *
     * @param resp
     * @param msg
     * @
     */
    private void successMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 0)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("successMsg response out error");
        }
    }

}
